package com.wust.baby.picture;
import java.io.BufferedInputStream;
import java.io.File;  
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;  
import java.util.List;

import com.wust.R;
import com.wust.footprint.FirstActivity;
import com.wust.footprint.diaryList;
import com.wust.menu.FirstGroupTab;
  
import android.annotation.SuppressLint;
import android.app.Activity;  
import android.content.Context;  
import android.content.Intent;  
import android.graphics.Bitmap;  
import android.graphics.BitmapFactory;  
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;  
import android.media.ThumbnailUtils;  
import android.os.AsyncTask;  
import android.os.Bundle;  
import android.os.Environment;  
import android.view.View;  
import android.view.ViewGroup;  
import android.view.Window;  
import android.view.WindowManager;
import android.widget.AdapterView;  
import android.widget.AdapterView.OnItemClickListener;  
import android.widget.BaseAdapter;  
import android.widget.GridView;  
import android.widget.ImageView;  
import android.widget.Toast;  
  
public class ImageGridActivity extends Activity {  
    private GridView sdcardImages;  
    private FileAdapter fileAdapter;  
    List<String> it = null;
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);   
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setContentView(R.layout.pic_main);  
		//影藏顶部程序名称 写在setContentView(R.layout.gallery_1);之前，不然报错
		//影藏顶部电量等图标
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
				WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        
    }  
    @Override
    protected void onPause() {
    	// TODO Auto-generated method stub
    	 final GridView grid = sdcardImages;  
         final int count = grid.getChildCount();  
         ImageView v = null;  
         for (int i = 0; i < count; i++) {  
             v = (ImageView) grid.getChildAt(i);  
             ((BitmapDrawable) v.getDrawable()).setCallback(null);  
         }    
    	super.onPause();
    }
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	
        setupViews();  
        setProgressBarIndeterminateVisibility(true);  
        new AsyncLoadedImage().execute();  
    	super.onResume();
    }
    @Override  
    public void onBackPressed() {   
        //把后退事件交给子Activity处理  
		Intent intent = new Intent(ImageGridActivity.this, FirstActivity.class);  
        // 把Activity转换成一个Window，然后转换成View  
        Window w = FirstGroupTab.group.getLocalActivityManager()  
                .startActivity("FirstActivity",intent);  
        View view = w.getDecorView();  
        //设置要跳转的Activity显示为本ActivityGroup的内容  
        FirstGroupTab.group.setContentView(view);  
       
    } 
    /* 
     * 初始化文件浏览View 
     */  
    private void setupViews() {  
        sdcardImages = (GridView) findViewById(R.id.sdcard);  
        sdcardImages.setOnItemClickListener(new fileListener());  
        fileAdapter = new FileAdapter(getApplicationContext());  
        sdcardImages.setAdapter(fileAdapter);  
    }  
  
    /* 
     * 释放Bitmap内存 
     */  
    protected void onDestroy() {  
        super.onDestroy();  
       
    }  
  
    /* 
     * 刷新Adapter 
     */  
    private void addImage(LoadedImage... value) {  
        for (LoadedImage image : value) {  
            fileAdapter.addPhoto(image);  
            fileAdapter.notifyDataSetChanged();  
        }  
    }  
  
    /* 
     * 点击监听 
     */  
    class fileListener implements OnItemClickListener {  
        public void onItemClick(AdapterView<?> paramAdapterView,  
                View paramView, int paramInt, long paramLong) {  
            LoadedImage loadedImage = (LoadedImage) sdcardImages.getItemAtPosition(paramInt);  
              
            //showMsg(""+loadedImage.getPicPath());  
              System.out.println("picPath--------------"+loadedImage.getPicPath());
            Intent intentPicView = new Intent(getBaseContext(),  ImageSwitcherAndGalleryDemoActivity.class);  
            intentPicView.putExtra("picPath", loadedImage.getPicPath());  
            startActivity(intentPicView);  
            loadedImage.mBitmap.recycle();
        }  
    }  
    private boolean getImageFile(String fName) {
        boolean re;
        String end = fName
                      .substring(fName.lastIndexOf(".") + 1, fName.length())
                      .toLowerCase();
        if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                      || end.equals("jpeg") || end.equals("bmp")) {
               re = true;
        } else {
               re = false;
        }
        return re;
 }
    private List<String> getSD() {
        it = new ArrayList<String>();
        File f = new File(ConstDefine.PATH);
        //File f = new File(Environment.getExternalStorageDirectory()+"/");
        File[] files = f.listFiles();

        for (int i = 0; i < files.length; i++) {
               File file = files[i];
               if (getImageFile(file.getPath()))
                      it.add(file.getPath());
        }
        return it;
 }
    /* 
     * 异步加载缩略图到LoadedImage然后调用addImage方法更新Adapter 
     */  
    @SuppressLint("NewApi")
	class AsyncLoadedImage extends AsyncTask<Object, LoadedImage, Object> {  
        @Override  
        protected Object doInBackground(Object... params) {  
               
            File file = new File(ConstDefine.PATH);  
            if (!file.exists()) {  
                file.mkdirs();  
            } else {  
              //  File[] files = file.listFiles(); 
            	getSD();
                
                Bitmap bitmap;  
                Bitmap newBitmap;  
                for (int i = 0; i < it.size(); i++) {  
                    
                    try {  
                        BitmapFactory.Options options = new BitmapFactory.Options(); 
                       
                        options.inSampleSize = 10;  
                        options.inJustDecodeBounds=true;
                        bitmap = BitmapFactory.decodeFile(it.get(i));
                       
                        
                        options.inJustDecodeBounds = false;
                        options.inInputShareable = true;
                        options.inPurgeable = true;
                        newBitmap=BitmapFactory.decodeFile(it.get(i), options);
                        newBitmap = ThumbnailUtils.extractThumbnail(bitmap,  
                               120, 120);  
                        bitmap.recycle();  
                        if (newBitmap != null) {  
                            publishProgress(new LoadedImage(newBitmap,it.get(i) ));  
                        }  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
            return null;  
        }  
      
        //实时更新UI  onProgressUpdate()方法的参数对应于doInBackground中publishProgress方法的参数，同时也对应于  
        //doInBackground的第二个参数  
        @Override  
        public void onProgressUpdate(LoadedImage... value) {  
            addImage(value);  
        }  
  
        //更新UI结束后的处理  
        @Override  
        protected void onPostExecute(Object result) {  
            setProgressBarIndeterminateVisibility(false);  
        }  
    }  
  
    /* 
     * Adapter 
     */  
    class FileAdapter extends BaseAdapter {  
  
        private Context mContext;  
        private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();  
  
        public FileAdapter(Context context) {  
            mContext = context;  
        }  
  
        public void addPhoto(LoadedImage photo) {  
            photos.add(photo);  
        }  
  
        public int getCount() {  
            return photos.size();  
        }  
  
        public Object getItem(int position) {  
            return photos.get(position);  
        }  
  
        public long getItemId(int position) {  
            return position;  
        }  
  
        public View getView(int position, View convertView, ViewGroup parent) {  
            final ImageView imageView;  
            if (convertView == null) {  
                imageView = new ImageView(mContext);  
            } else {  
                imageView = (ImageView) convertView;  
            }  
            imageView.setBackgroundColor(Color.BLACK);
       //     imageView.setMaxHeight(maxHeight)
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);  
            imageView.setPadding(0, 1, 1, 1);  
            imageView.setImageBitmap(photos.get(position).getBitmap());  
            return imageView;  
        }  
    }  
  
    /* 
     * 这是个保存bitmap的类，加入Adapter的ArrayList中，随着addImage更新Adapter 
     */  
    private static class LoadedImage {  
        String picPath;  
        Bitmap mBitmap;  
  
        LoadedImage(Bitmap bitmap,String picPath ) {  
            this.mBitmap = bitmap;  
            this.picPath=picPath;  
        }  
  
        public Bitmap getBitmap() {  
            return mBitmap;  
        }  
          
        public String getPicPath() {  
            return picPath;  
        }  
      
          
    }  
  
    /* 
     * 消息提示 
     */ 
    /*
    private Toast toast;  
  
    public void showMsg(String arg) {  
        if (toast == null) {  
            toast = Toast.makeText(this, arg, Toast.LENGTH_SHORT);  
        } else {  
            toast.cancel();  
            toast.setText(arg);  
        }  
        toast.show();  
    }  */
}  